import React  from 'react';
import PropTypes from 'proptypes';
import CollapseIcon from './collapse-icon.jsx';
import TableSubmenu from './table-submenu.jsx';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import List from '@mui/material/List';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
const sqlectron  = window.myremote.sqlectron;
const CLIENTS = sqlectron.db.CLIENTS;

export default function DatabaseItem(props){
  const [contextMenu, setContextMenu] = React.useState(null);
  const [state, setState] = React.useState({menuitems:[]});
  const handleContextMenu = (event) => {
    event.preventDefault();
    setContextMenu(
      contextMenu === null
        ? {
            mouseX: event.clientX + 2,
            mouseY: event.clientY - 6,
          }
        : // repeated contextmenu when it is already open closes it with Chrome 84 on Ubuntu
          // Other native context menus might behave different.
          // With this behavior we prevent contextmenu from the backdrop to re-locale existing context menus.
          null,
    );
  };
  const handleClose = () => {
    setContextMenu(null);
  };
  React.useEffect(()=>{
    buildContextMenu();
  },[]);

  const buildContextMenu=()=> {
    console.log("buildContextMenu======")
    const {
      client,
      database,
      item,
      dbObjectType,
      onExecuteDefaultQuery,
      onExecuteEditTable,
      onGetSQLScript,
    } = props;
    let menus=state.menuitems
    let index=menus.length;
    if (dbObjectType === 'Table' || dbObjectType === 'View') {
      console.log("Table")
      menus.push(
        <MenuItem key={index} onClick={()=>{
          props.onExecuteDefaultQuery(database, item);
          setContextMenu(null);
        }}>Select Rows (with limit)</MenuItem>
      );
      index+=1;
    }
    if (dbObjectType === 'Table') {
      menus.push(
        <MenuItem  key={index} onClick={()=>{
          props.onExecuteEditTable(database, item);
          setContextMenu(null);
        }}>EditTable</MenuItem>
      );
      index+=1;
    }
    const { disabledFeatures } = CLIENTS.find(
      dbClient => dbClient.key === client
    );
    if (!disabledFeatures || !~disabledFeatures.indexOf('scriptCreateTable')) {
      menus.push(
        <MenuItem  key={index} onClick={()=>{
          props.onGetSQLScript(database, item,'CREATE',dbObjectType);
          setContextMenu(null);
        }}>Create Statement</MenuItem>
      );
      index+=1;
    }

    if (dbObjectType === 'Table') {
      const actionTypes = ['SELECT', 'INSERT', 'UPDATE', 'DELETE'];
      const labelsByTypes = {
        SELECT: 'Select Statement',
        INSERT: 'Insert Statement',
        UPDATE: 'Update Statement',
        DELETE: 'Delete Statement',
      };

      actionTypes.forEach((actionType) => {
        return menus.push(
          <MenuItem  key={index} onClick={()=>{
            props.onGetSQLScript(database, item,actionType,dbObjectType);
            setContextMenu(null);
          }}>{labelsByTypes[actionType]}</MenuItem>
        );
        index+=1;
      });
    }
    setState({...state, menuitems: menus });
  }

  const toggleTableCollapse=()=> {
    setState({ tableCollapsed: !state.tableCollapsed });
  }

  const renderSubItems=({ schema, name })=> {
    const {
      columnsByTable,
      triggersByTable,
      indexesByTable,
      database,
    } = props;

    if (!columnsByTable || !columnsByTable[name]) {
      return null;
    }

    const displayStyle = {};
    if (!state.tableCollapsed) {
      displayStyle.display = 'none';
    }

    return (
      <div style={displayStyle}>
        <TableSubmenu
          title="Columns"
          schema={schema}
          table={name}
          itemsByTable={columnsByTable}
          database={database}
        />
        <TableSubmenu
          collapsed
          title="Triggers"
          schema={schema}
          table={name}
          itemsByTable={triggersByTable}
          database={database}
        />
        <TableSubmenu
          collapsed
          title="Indexes"
          schema={schema}
          table={name}
          itemsByTable={indexesByTable}
          database={database}
        />
      </div>
    );
  }


  const { database, item, style, onSelectItem, dbObjectType } = props;
  const hasChildElements = !!onSelectItem;
  const onSingleClick = hasChildElements
    ? () => {
        onSelectItem(database, item);
        toggleTableCollapse();
      }
    : () => {};

  const collapseArrowDirection = state.tableCollapsed ? 'down' : 'right';
  const tableIcon = (
    <i
      className="table icon"
      style={{ float: 'left', margin: '0 0.3em 0 0' }}
    />
  );

  const { schema, name } = item;
  const fullName = schema ? `${schema}.${name}` : name;

  return (
    <div>
      <span
        style={style}
        className="item"
        onClick={onSingleClick}
        onDoubleClick={()=>{props.onExecuteDefaultQuery(props.database,props.item);}}
        onContextMenu={handleContextMenu}
      >
        {dbObjectType === 'Table' ? (
          <CollapseIcon arrowDirection={collapseArrowDirection} />
        ) : null}
        {dbObjectType === 'Table' ? tableIcon : null}
        {fullName}
      </span>
      {renderSubItems(item)}
      <Menu
        open={contextMenu !== null}
        onClose={handleClose}
        anchorReference="anchorPosition"
        anchorPosition={
          contextMenu !== null
            ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
            : undefined
        }
      >
      {
        state.menuitems
      }
      </Menu>
    </div>
  );
}
